var CompositeDisposable, AtomMiku, MikuView;
var $ = require('jquery');

MikuView = require('./miku-view');

CompositeDisposable = require('atom').CompositeDisposable;

module.exports = AtomMiku = {
    mikuView: null,
    elem: null,
    toggle: null,
    typing: null,
    subscriptions: null,
    disposableEditor: null,
    activate: function(state) {
        var that = this;
        this.mikuView = new MikuView(state.mikuViewState);
        this.elem = this.mikuView.getElement();
        console.log(this.elem);
        document.querySelector('.workspace').appendChild(this.elem);
        this.mikuView.initEventBind();
        this.mikuView.miku = window.frames[this.mikuView.iframeName];
        this.subscriptions = new CompositeDisposable;
        var editor = atom.workspace.getActiveTextEditor();
        /*
        * 注册atom事件
        * toggle 事件暂存在this.subscriptions
        * textChange事件单独存
        * */
        this.subscriptions.add(atom.commands.add('atom-workspace', {
            'AtomMiku:toggle': ( function(_this) {
                return function() {
                    return _this.toggle();
                };
            } )(this)
        }));
        /*
        * 插件激活时监听当前
        * */
        this.typing = editor.onDidChange(function() {
            that.mikuView.addFrame(1.5);
        });

        /*
        * 切换时
        * */
        this.subscriptions.add(atom.workspace.onDidChangeActivePaneItem(function(item){
            if(item && item.constructor && item.constructor.name && item.constructor.name == 'TextEditor'){
                /*
                * 同一时间只有一个editor注册change事件
                * */
                that.typing.dispose();
                that.typing = null;
                that.typing = item.onDidChange(function() {
                    that.mikuView.addFrame(1.5);
                });
            }
        }))
    },
    deactivate: function() {
        this.subscriptions.dispose();
        this.typing.dispose();
        $(this.elem).html('');
    },
    serialize: function() {
        return {
            mikuViewState: this.mikuView.serialize()
        };
    },
    toggle: function() {
         if (this.elem.style.display == 'block') {
             this.mikuView.pause();
             this.elem.style.display = 'none';
         } else {
             this.mikuView.play();
             this.elem.style.display = 'block';
         }
    }
};

// ---
// generated by coffee-script 1.9.2
